package com.jdy.haoduoaiteacher.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.CartoonVo;
import com.jdy.haoduoaiteacher.model.CategoryItem;
import com.jdy.haoduoaiteacher.model.CustomAlbumItem;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.util.ACache;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;


public class CustomExpandListActivity extends BaseActivity {

    private CategoryItem categoryItem = null;
    private String title;
    private JSONArray jsonArr;
    private ACache mCache;
    private boolean isEdit;


    ExpandableListAdapter mAdapter = null;
    ExpandableListView expandableListView;

    private ArrayList<CartoonVo> mArrayList = null;

    ArrayList<CustomAlbumItem> listt = new ArrayList<>();

    private ArrayList<CustomAlbumItem> mArrayListAlbum = null;

    /**
     * 加载数据
     */
    private void loadData() {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                //dismissLoading();
                if (result.isSuccess()) {

                    if (Tools.isNotNullStr(result.data)) {
                        try {
                            JSONObject json = new JSONObject(result.data);
                            String data = json.optString("data");
                            final JSONArray array = new JSONArray(data);

                            new Thread() {
                                @Override
                                public void run() {
                                    if (jsonArr != null) {
                                        mCache.remove(title);
                                    }
                                    mCache.put(title, array);
                                }

                            }.start();

                            mArrayList.clear();

                            for (int i = 0; i < array.length(); i++) {
                                JSONObject obj = ((JSONObject) array.opt(i));

                                if (Tools.isNotEmpty(obj.toString())) {
                                    CartoonVo itemVo = JsonSerializer.getInstance()
                                            .deserialize(obj.toString(), CartoonVo.class);
                                    mArrayList.add(itemVo);
                                }

                            }
                        } catch (Exception e) {
                        }
                        setView();
                    }


                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                if (lu == null) {
                    lu = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                if (categoryItem != null) {
                    param_.put("category_id", categoryItem.id);
                }

                param_.put("page", 1);
                param_.put("page_size", 50);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                return HttpUtils.startRequest(HttpUtils.HOST_API
                                + "/api/2.0/catalog/teacher/album", param_,
                        HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }

    /**
     * 初始化方法
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main22_teacher);

        mCache = ACache.get(this);
        mArrayList = new ArrayList<>();
        mArrayListAlbum = new ArrayList<>();


        mTvUpright.setText("提交");
        mTvUpright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listt.clear();
                for (CustomAlbumItem item : mArrayListAlbum) {
                    if (item.selected) {
                        listt.add(item);
                    }
                }
                if (listt.isEmpty()) {
                    toastShow("请选择课程");
                } else {
                    if (listt.size() > 5) {
                        toastShow("最多只能选择5条");
                    } else {
                        Intent resultIntent = new Intent();
                        resultIntent.putExtra("selectdata", listt);
                        setResult(RESULT_OK, resultIntent);

                        finish();
                    }
                }
            }
        });
        this.mTvUpright.setVisibility(View.VISIBLE);
        this.mTvUpright.setTextColor(Color.argb(255, 255, 255, 255));

        Intent intent = getIntent();
        if (intent.getSerializableExtra("categoryitem") != null) {
            categoryItem = (CategoryItem) intent.getSerializableExtra("categoryitem");
            title = categoryItem.name;

            setTitle(categoryItem.name);
            loadData();
        }


        Bundle bundle = getIntent().getExtras();
        isEdit = bundle.getBoolean("isEdit", false);
    }


    private void getEpisode(final int album_id, final int groupPosition) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {

                    if (Tools.isNotNullStr(result.data)) {

                        try {
                            JSONObject json = new JSONObject(result.data);
                            String data = json.optString("data");
                            JSONArray array = new JSONArray(data);

                            mArrayListAlbum.clear();

                            for (int i = 0; i < array.length(); i++) {
                                JSONObject obj = ((JSONObject) array.opt(i));

                                if (Tools.isNotEmpty(obj.toString())) {
                                    CustomAlbumItem itemVo = JsonSerializer.getInstance().deserialize(
                                            obj.toString(), CustomAlbumItem.class);

                                    if (Tools.isEmpty(itemVo.album_name)) {
                                        itemVo.album_name = mArrayList.get(groupPosition).name;
                                    }
                                    mArrayListAlbum.add(itemVo);
                                }

                            }
                        } catch (Exception e) {
                        }

                        //  setView(isLoadMore);
                        // mAdapter.notifyAll();
                        expandableListView.expandGroup(groupPosition);
                    }

                } else {
                    if (Tools.isNotNullStr(result.data)) {
                        Toast.makeText(CustomExpandListActivity.this, result.data,
                                Toast.LENGTH_SHORT).show();
                    }

//                    storylistPullLayout.refreshFinish(PullToRefreshLayout.FAIL);
//                    storylistPullLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
                if (lu == null) {
                    lu = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                param_.put("album_id", album_id);

                param_.put("page", 1);
                param_.put("page_size", 50);
                return HttpUtils.startRequest(HttpUtils.HOST_API
                        + "/api/2.0/catalog/teacher/episode", param_, HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }


    private void setView() {
        mAdapter = new BaseExpandableListAdapter() {
//            // 子视图显示文字
//            private String[][] city = new String[][]{
//                    {"郑州市", "开封市", "新乡市", "安阳市", "南阳市"},
//                    {"石家庄市", "邯郸市", "保定市", "廊坊市"},
//                    {"济南市", "青岛市", "日照市", "烟台市", "威海市"},
//                    {"太原市", "大同市", "晋城市", "吕梁市", "长治市"}};
//
//            // 自己定义一个获得文字信息的方法
//            TextView getTextView() {
//                AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
//                        ViewGroup.LayoutParams.MATCH_PARENT, 64);
//                TextView textView = new TextView(CustomExpandListActivity.this);
//                textView.setLayoutParams(lp);
//                textView.setGravity(Gravity.CENTER_VERTICAL);
//                textView.setPadding(36, 0, 0, 0);
//                textView.setTextSize(20);
//                textView.setTextColor(Color.BLACK);
//                return textView;
//            }

            // 重写ExpandableListAdapter中的各个方法
            @Override
            public int getGroupCount() {
                return mArrayList.size();
            }

            @Override
            public Object getGroup(int groupPosition) {
                return mArrayList.get(groupPosition).name;
            }

            @Override
            public long getGroupId(int groupPosition) {
                return groupPosition;
            }

            @Override
            public int getChildrenCount(int groupPosition) {
                return mArrayListAlbum.size();/*city[groupPosition].length;*/
            }

            @Override
            public Object getChild(int groupPosition, int childPosition) {
                if (groupPosition < mArrayListAlbum.size()) {
                    return mArrayListAlbum.get(groupPosition).album_name;//city[groupPosition][childPosition];
                } else {

                    return "数据错误";
                }
            }

            @Override
            public long getChildId(int groupPosition, int childPosition) {
                return childPosition;
            }

            @Override
            public boolean hasStableIds() {
                return true;
            }

            @Override
            public View getGroupView(int groupPosition, final boolean isExpanded,
                                     View convertView, ViewGroup parent) {
                LinearLayout ll = new LinearLayout(CustomExpandListActivity.this);

                View v = LayoutInflater.from(CustomExpandListActivity.this).inflate(
                        R.layout.navigation_item, ll, false);

                ll.setOrientation(LinearLayout.HORIZONTAL);

                TextView tv_cc = (TextView) v.findViewById(R.id.tv_cc);
                tv_cc.setText(getGroup(groupPosition).toString());

                Drawable drawableLeft = getResources().getDrawable(
                        R.drawable.uncheckpic);
                drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(),
                        drawableLeft.getMinimumHeight());

                if (isExpanded) {
                    Drawable drawable = getResources().getDrawable(
                            R.drawable.upgray_arrow);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                            drawable.getMinimumHeight());
                    tv_cc.setCompoundDrawables(drawableLeft, null, drawable, null);
                } else {
                    Drawable drawable = getResources().getDrawable(
                            R.drawable.downgray_arrow);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(),
                            drawable.getMinimumHeight());
                    tv_cc.setCompoundDrawables(drawableLeft, null, drawable, null);
                }
                ll.addView(v);
                return ll;
            }

            @Override
            public View getChildView(int groupPosition, int childPosition,
                                     boolean isLastChild, View convertView, ViewGroup parent) {
                LinearLayout ll = new LinearLayout(CustomExpandListActivity.this);
                ll.setOrientation(LinearLayout.HORIZONTAL);


                View v = LayoutInflater.from(CustomExpandListActivity.this).inflate(
                        R.layout.story_number_listitem4addhabit_teacher, ll, false);


                final CustomAlbumItem ai = mArrayListAlbum.get(childPosition);
                final String album_name = ai.album_name;
                final String name = ai.title;
                final boolean isFav = ai.favorite;
                final String order = ai.sort + "";
                final String reslen = Tools.secToTime(ai.length);
                final String subtitle = "";

                TextView storynumber = (TextView) v
                        .findViewById(R.id.storynumber);
                TextView storytittle = (TextView) v
                        .findViewById(R.id.storytittle);

                TextView tv_storylist = (TextView) v
                        .findViewById(R.id.tv_storylist);

                if (mArrayListAlbum != null) {
                    if (storynumber != null) {
                        ai.sort = (childPosition + 1);
                        storynumber.setText(album_name + " 第" + childPosition + 1 + "集" + " ("
                                + reslen + ")");
                        if (Tools.isEmpty(subtitle)) {
                            storytittle.setText(name);
                        } else {
                            storytittle.setText(subtitle);
                        }
                    }
                }

                ll.addView(v);
                return ll;
            }

            @Override
            public boolean isChildSelectable(int groupPosition, int childPosition) {
                return true;
            }

        };


        expandableListView = findViewById(R.id.province);
        expandableListView.setAdapter(mAdapter);
        expandableListView.setGroupIndicator(null);

        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {

            }
        });

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {

                int count = expandableListView.getExpandableListAdapter().getGroupCount();
                for (int j = 0; j < count; j++) {
                    if (j != groupPosition) {
                        expandableListView.collapseGroup(j);
                    }
                }

            }
        });

        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {

                boolean expanded = parent.isGroupExpanded(groupPosition);
                if (!expanded) {
                    getEpisode(mArrayList.get(groupPosition).id, groupPosition);
                    return true;
                }
                return false;
            }
        });

        // 设置item点击的监听器
        expandableListView.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, final int childPosition, long id) {

                View vvv = v.findViewById(R.id.img_checkimg);
                if (vvv.getVisibility() == View.VISIBLE) {
                    vvv.setVisibility(View.GONE);
                    if (mArrayListAlbum != null && childPosition < mArrayListAlbum.size()) {
                        mArrayListAlbum.get(childPosition).selected = false;
                    }
                } else {

                    listt.clear();
                    for (CustomAlbumItem item : mArrayListAlbum) {
                        if (item.selected) {
                            listt.add(item);
                        }
                    }

                    if (isEdit) {
                        if (listt.size() >= 1) {
                            //toastShow("最多只能选择5条");
                        } else {
                            vvv.setVisibility(View.VISIBLE);
                            if (mArrayListAlbum != null && childPosition < mArrayListAlbum.size()) {
                                mArrayListAlbum.get(childPosition).selected = true;
                            }
                        }
                    } else {
                        if (listt.size() >= 5) {
                            toastShow("最多只能选择5条");
                        } else {
                            vvv.setVisibility(View.VISIBLE);
                            if (mArrayListAlbum != null && childPosition < mArrayListAlbum.size()) {
                                mArrayListAlbum.get(childPosition).selected = true;
                            }
                        }
                    }


                }

                return false;
            }
        });
    }
}